package ltd.followkba.page;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.kcbsdk.ABean;
import com.kcbsdk.AFileBase;
import com.kcbsdk.ALoadBean;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyManage.AUserFileType;
import com.kcbsdk.MyManage.AUserInfo;
import com.kcbsdk.MyWorks.AFileInfo;

import java.util.ArrayList;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.task.App32;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BAppWorks;
import ltd.followkba.task.BFileBase;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static ltd.advskin.view.KcListView.LIST_PULL_LOAD_MORE;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class RankListPage extends BaseList {
    private List<BAppWorks>[] mBAppWorks;
    private byte gWorksType;

    private boolean isBusy;
    private List<ALoadBean> mAUserLoad;
    private List<ALoadBean> mAFileLoad;
    private BAppWorks mTempBAppWorks;


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_rank_list);
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvRank);
        gWorksType = MAPP.mBDbsAccount.WorksType;
        String text = String.format("%s榜单列表",  MAPP.mWorksName[gWorksType]);
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
//        tvSelectRank = findViewById(R.id.kbtCleanRank);
        findViewById(R.id.kbtCleanRank).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                       // 刷新
//                getAllWorksList(false);
            }
        });

        findViewById(R.id.kbtAllRank).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                       // 全部
//                getAllWorksList(true);
            }
        });

        if (MAPP.mKcBRankInfo != null) {
            mBAppWorks = new List[MAPP.mKcBRankInfo.length];
            gTabSelect = (byte) MDBS.getFreeInt(gWorksType, "RankSlect");
            initPageListView(MAPP.mKcBRankInfo.length);
            App32.setUser(MAPP.mManageAccount);
            mAUserLoad = new ArrayList<>();
            mAFileLoad = new ArrayList<>();
        }else {
            MTOAST("BRankInfo数据还没有准备好...");
            setClose();
        }
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (mMyWorks.isEventDataRefresh()){
                    showInfo();
                    setListView(gTabSelect);
                }
            }
        });
        getRankList(gTabSelect);
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        setClose();
    }
    private void showInfo() {
        int tabSel = getTabList();
        if (tabSel > 0) {
            tabSel -= 1;
//            MLOG(String.format("RankB mApp32A %s %s", tabSel, mBAppWorks[tabSel]));
            getRankList(tabSel);
            setListView(gTabSelect, (List) mBAppWorks[gTabSelect]);
//            MSKIN.setText(text, tvSelectRank);
        }
    }
    private void getRankList(int tabSel){
//        MLOG(String.format("RankB AAA %s %s %s", tabSel, isBusy, mBAppWorks[tabSel]));
        if (mBAppWorks[tabSel] != null) {
            setListView(gTabSelect, (List) mBAppWorks[gTabSelect]);
            return;
        }
        if (isBusy) {
            return;
        }
        MLOG(String.format("RankB AAB %s %s %s", tabSel, isBusy, mBAppWorks[tabSel]));
        isBusy = true;
        new TaskFree(tabSel, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                int tabSel = (int)object;
                if (isThread){
                        MLOG(String.format("RankB AAC %s %s %s %s", tabSel, gWorksType, MAPP.mKcBRankInfo[tabSel].UserID, MAPP.mKcBRankInfo[tabSel].Name, mBAppWorks[tabSel]));
                        BFileBase[] bFileBases = App32.getRankList(gWorksType, MAPP.mKcBRankInfo[tabSel], 333);
                        MLOG(String.format("RankB AAD %s %s", tabSel, bFileBases!=null?bFileBases.length:0));
//                            MLOG(String.format("RankA mApp32C %s %s", gsUserIdS, mBFileBase != null ? mBFileBase.length : 0));
                        if (bFileBases != null) {
                            List<BAppWorks> lists = new ArrayList<>();
                            for (int index = 0; index < bFileBases.length; index++){
                                BAppWorks bAppWorks = new BAppWorks();
                                bAppWorks.UserID = bFileBases[index].UserID;
                                bAppWorks.FileID = bFileBases[index].FileID;
                                bAppWorks.UserIdS = bFileBases[index].UserIdS;
                                bAppWorks.WorksIdS = bFileBases[index].WorksIdS;
                                lists.add(bAppWorks);
                            }
                            mBAppWorks[tabSel] = lists;
                        }
                    return;
                }
                showInfo();
                isBusy = false;
            }
        });
    }
    private void selectWorks(View view){
        AFileBase aFileBase = (AFileBase) view.getTag();
        if (aFileBase != null) {
            new TaskFree(aFileBase, new TaskFree.Listener() {
                @Override
                public void onMessage(boolean isThread, Object object) {
                    AFileBase aFileBase = (AFileBase)object;
                    if (isThread){
                        BAppUser bAppUser = App32.getUserInfo(String.format("%s", aFileBase.UserID));
                        MDBS.setBAppUser(bAppUser);
                        MDBS.setFreeText(gWorksType, "OperationUser", bAppUser.UserIdS);

                        BAppWorks bAppWorks = App32.getWorksInfo(String.format("%s", aFileBase.UserID), String.format("%s", aFileBase.FileID));
                        MDBS.setBAppWorks(bAppWorks);
                        MDBS.setFreeInt(gWorksType, "WorksType", bAppWorks.WorksType);
                        MDBS.setFreeText(gWorksType, "UserIdS", bAppWorks.UserIdS);
                        MDBS.setFreeText(gWorksType, "IdS", bAppWorks.WorksIdS);
                        mTempBAppWorks = bAppWorks;
                        MLOG(String.format("RankA SelectA %s %s %s", gWorksType, bAppWorks.UserIdS, bAppWorks.WorksIdS));
                        return;
                    }
                    setPageResult(mTempBAppWorks);
                    setClose();
                    MTOAST("已选择作品 "+mTempBAppWorks.WorksName);
                }
            });
        }
    }


    private static final int[] item_rank_list = new int[]{
            R.layout.item_rank_list, 8,
            R.id.kbiHeadRank, R.id.kbtNameRank, R.id.tvInfoRank, R.id.tvDateRank,
            R.id.kbiCoverRank, R.id.tvWorksRank, R.id.tvStateRank, R.id.tvIntroRank,
    };
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, item_rank_list, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                switch (type) {
                    case LIST_PULL_LOAD_MORE :
                        new TaskFree(null, new TaskFree.Listener() {
                            @Override
                            public void onMessage(boolean isThread, Object object) {
                                if (isThread){
                                }
                            }
                        });
                        showInfo();
                        MLOG(String.format("RecordListPage 更多"));
                        break;
                }
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                Object object = getListView(tab, position);
                if (object instanceof AFileBase){
                    AFileBase aFileBase = (AFileBase) object;
                    String text;
//                    MLOG(String.format("RankA A %s %s_%04x", position, aFileBase.UserID, aFileBase.FileID));//,  %s(%s), aFileBase, holder.mView[4]));
                    MSKIN.showUserHead(AUserFileType.IMG_SMALL, aFileBase, holder.mView[0]);
                    MSKIN.showUserName(aFileBase, holder.mView[1]);
                    ABean aBean = mMyWorks.fetchUserDetail(aFileBase, mAUserLoad);
                    if (aBean.ErrorStr == null){
                        text = MAPP.getUser((AUserInfo)aBean.mObject, gWorksType);
                        MSKIN.setText(text, holder.mView[2]);
                    }
                    MSKIN.showWorksName(aFileBase, holder.mView[5]);
                    aBean = mMyWorks.fetchFileDetail(aFileBase, mAFileLoad);
                    if (aBean.ErrorStr == null){
                        AFileInfo aFileInfo = (AFileInfo)aBean.mObject;
                        MSKIN.setText(mMyUtils.getSmartDate(aFileInfo.ReleaseDate), holder.mView[3]);  // 已发布作品的时间
                        MSKIN.showWorksCover(aFileInfo, holder.mView[4]);
                        MSKIN.setText(MAPP.getWorks(aFileInfo), holder.mView[6]);

                    }else {
                        MSKIN.showWorksCover((String) null, holder.mView[4]);
                    }
                    MSKIN.setText(mMyUtils.getFileIntro(aFileBase), holder.mView[7]);
                    holder.mItemView.setTag(aFileBase);
                    holder.mItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectWorks(v);
                        }
                    });
                }
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", "", "");
        mKcListView[tab].setTabNumber(tab);
        mKcListView[tab].setSpaceHeight(MRAM.g4ScreenWidth);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        gTabQty = (byte) tabQty;
        TabLayout tabLayout = findViewById(R.id.tlRank);;
        ViewPager viewPager = findViewById(R.id.vpRank);
        mKcListView = new KcListView[tabQty];
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return MAPP.mKcBRankInfo.length;
            }
            @Override
            public CharSequence getPageTitle(int position) {
                return MAPP.mKcBRankInfo[position].Name;
            }
            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                KcListView kcListView = new KcListView(getActivity(), null);
                initListView(position, kcListView);
                container.addView(kcListView);
                setTabList(position);                               // 设置Tab的位置
                return kcListView;
            }
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mKcListView[position]);
                mKcListView[position] = null;
            }
        };
        viewPager.setAdapter(mPagerAdapter);
        viewPager.setCurrentItem(gTabSelect);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);       // 设置TabLayout的模式   MODE_SCROLLABLE为滑动模式  MODE_FIXED为不滑动模式
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabSelected(TabLayout.Tab tab) {   // 顶部Tab选择
                byte tabSel = (byte) tab.getPosition();
                if (gTabSelect != tabSel) {                 // Tab的选择
                    gTabSelect = tabSel;
                    setTabList(tabSel);                     // 设置Tab的位置
                    MDBS.setFreeInt(gWorksType, "RankSlect", tabSel);
                }
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
}


